import React, { useState } from "react";
import { View, Navigator, Text, Picker } from "@tarojs/components";
import {
  AtIcon,
  AtMessage,
  AtToast,
  AtFloatLayout,
  AtList,
  AtListItem,
  AtButton
} from "taro-ui";
import Taro from "@tarojs/taro";
import {
  error,
  isDeadLineTime,
  isLogin,
  showMes,
  getLocalStore,
  setLocalStore,
  showAppointMsg
} from "../../utils/util";
import {
  orderTime,
  getUserStatus,
  getOrderTime,
  checkOrderNum
} from "../../api/user";

export default function List() {
  // 列表项
  const listMenu = [
    {
      name: "工作室简介",
      ico: "align-right",
      url: "/pages/description/index"
    },
    {
      name: "我要报名",
      ico: "bookmark",
      url: "/pages/signUp/index"
    },
    {
      name: "预约日期",
      ico: "calendar",
      url: "none"
    },
    {
      name: "排队面试",
      ico: "tags",
      url: "/pages/lineUp/index"
    },
    {
      name: "结果通知",
      ico: "bell",
      url: "/pages/result/index"
    }
  ];

  //是否展示弹出框
  const [showFloatLayout, setShow] = useState(false);

  //预约的时间以及日期
  const [date, setDate] = useState("2022-05-28");

  //已经预约的时间
  const [orderDate, setOrderDate] = useState("");

  //日期选择器的title
  const [title, setTitle] = useState("请选择日期");

  //面试日期范围
  const dateRange = {
    start: "2022-05-28",
    end: "2022-06-02"
  };
  //面试时间范围
  const timeRange = {
    start: "00:00",
    end: "22:30"
  };
  /**
   * 弹出AtFloatLayout,预约日期
   * @param
   */
  const makeAppointment = async () => {
    //发送请求，查看用户的预约时间
    //展示弹出框
    const res = await getOrderTime(getLocalStore("openid"));
    if (res.data !== null) {
      setOrderDate(res.data);
      setDate(res.data.replace(/\//g, "-"));
      setTitle("修改时间");
    } else {
      setOrderDate("");
      setTitle("请选择时间");
    }

    setShow(true);
  };

  /**
   * 用户修改日期
   */
  const onDateChange = event => {
    setDate(event.detail.value);
  };

  /**
   * 用户确认提交预约时间
   */
  const confirmTime = async () => {
    const openid = getLocalStore("openid");
    //先查询该时间的预约人数
    const { data } = await checkOrderNum(date, openid);
    console.log(data);

    const dayLimit = 12;
    //人数如果大于限定人数
    if (parseInt(data) + 1 > dayLimit) {
      showMes("该日期预约人数已经超过一定人数，请选择其它时间");
    } else {
      //预约该天
      const orderRes = await orderTime({
        date: date,
        openid
      });
      console.log(orderRes);
      if (orderRes.code === "1") {
        //预约成功,关闭弹出框
        showMes("预约成功");
        setLocalStore("order", true);
        setShow(false);
      }
    }
  };

  //用户关闭弹出框
  const handleClose = () => {
    setShow(false);
  };
  /**
   * 跳转到url页面，要判断是否登录
   * @param url
   */
  const navigationTo = async (url: string) => {
    //获取用户状态
    const getStatusRes = await getUserStatus(getLocalStore("openid"));
    const status = getStatusRes.data;
    const r = isDeadLineTime(Date.now());
    switch (url) {
      //预约面试
      case "none":
        //判断是否授权登录
        if (!isLogin()) return showMes("请先授权登录");
        //只有用户处于报名且还没面试状态才可以预约
        if (status === "1") {
          makeAppointment();
        } else {
          showMes("你暂时不可预约");
        }
        break;
      case "/pages/signUp/index":
        //先判断是否截止
        if (r) {
          return showMes("报名已经截止了哦");
        } else if (!isLogin()) {
          //再判断是否登录
          return showMes("请先授权登录哦");
        } else {
          Taro.navigateTo({
            url
          });
        }
        break;
      case "/pages/description/index":
        //详情页面直接跳
        Taro.navigateTo({
          url
        });
        break;
      case "/pages/lineUp/index":
        //先判断用户是否登录
        if (!isLogin()) {
          showMes("请先授权登录哦");
        } else if (status !== "1") {
          //报名还没面试状态才可以进来
          showMes(showAppointMsg(status));
        } else {
          //获取预约时间
          let { data } = await getOrderTime(getLocalStore("openid"));
          if (data) {
            data = data.replace(/-/g, "/");
            //当天的6:40到11：30才可以进行排队
            const startTime = new Date(data + " " + timeRange.start).getTime();
            const endTime = new Date(data + " " + timeRange.end).getTime();
            console.log(startTime);
            console.log(endTime);

            const now = Date.now();
            //只有当在特定两个时间范围内才可排队
            if (startTime <= now && now <= endTime) {
              Taro.navigateTo({
                url
              });
            } else {
              showMes("当前时间还不允许排队哦");
            }
          } else {
            showMes("请先预约时间再来排队");
          }
        }
        break;
      default:
        //其余的需要判断是否登录
        if (isLogin()) {
          Taro.navigateTo({
            url
          });
        } else {
          showMes("请先授权登录哦");
        }
    }
  };

  return (
    <View className="list">
      <AtMessage />
      {listMenu.map((listItem, i) => (
        // <Navigator url={listItem.url} className='list-item'>
        <View className="list-item">
          <View
            className="fx-v-c clitem"
            onClick={() => navigationTo(listItem.url)}
          >
            <AtIcon value={listItem.ico} size="17" className="ico" />
            {listItem.name}
          </View>
        </View>
        // </Navigator>
      ))}
      <AtFloatLayout
        isOpened={showFloatLayout}
        title="预约面试"
        onClose={() => {
          handleClose();
        }}
      >
        <View className="float-container">
          <View className="user-time">
            {orderDate === ""
              ? ""
              : `已预约时间：${orderDate.replace(/\//g, "-")}`}
          </View>
          <View className="date-container">
            <View className="word">日期</View>
            <View>
              <Picker
                mode="date"
                onChange={onDateChange}
                start={dateRange.start}
                end={dateRange.end}
                value={date}
              >
                <AtList>
                  <AtListItem title={title} extraText={date} />
                </AtList>
              </Picker>
            </View>
          </View>
          <View className="submit-button" onClick={confirmTime}>
            提交
          </View>
        </View>
      </AtFloatLayout>
    </View>
  );
}
